package com.spring5.learning.optional;

import java.util.Objects;
import java.util.Optional;

import org.junit.Test;

/**
 * @author xin
 * @version 1.0
 */
public class Main {

    @Test
    public void map() {
        User user = create();
        System.out.println(getCity(user));
    }

    @Test
    public void mapNew() {
        System.out.println(getCityByOptional(create()));
    }

    @Test
    public void print() {
        printUserName(create());
        printUserNameByOptional(create());

        //printUserName(null);
        //printUserNameByOptional(null);
    }

    @Test
    public void user() {
        printUserNameByOptional(getUser(create()));
        printUserNameByOptional(getUserByOptional(create()));
    }


    private User getUser(User user) {
        if (Objects.nonNull(user)) {
            if (Objects.equals("xin", user.getName())) {
                return user;
            }
            return null;
        } else {
            User result = new User();
            result.setName("xin");
            return result;
        }
    }


    private User getUserByOptional(User user) {
        return Optional.ofNullable(user)
                .filter(u -> Objects.equals("xin", u.getName()))
                .orElseGet(() -> {
                    User result = new User();
                    result.setName("xin");
                    return result;
                });
    }

    private void printUserName(User user) {
        if (Objects.nonNull(user)) {
            System.out.println(user.getName());
        }
    }

    private void printUserNameByOptional(User user) {
        Optional.ofNullable(user).ifPresent(u -> System.out.println(u.getName()));
    }

    private String getCity(User user) {
        if (Objects.nonNull(user)) {
            Address address = user.getAddress();
            if (Objects.nonNull(address)) {
                return address.getCity();
            }
        }
        throw new RuntimeException("不存在");
    }


    private String getCityByOptional(User user) {
        return Optional.ofNullable(user)
                .map(User::getAddress)
                .map(Address::getCity)
                .orElseThrow(() -> new RuntimeException("不存在"));
    }


    private User create() {
        Address address = new Address.Builder().province("广东")/*.city("广州")*/.area("天河").address();
        User user = new User();
        user.setName("xin");
        user.setPhone("110");
        user.setAddress(address);
        return user;
    }

}
